﻿using PIMS.DBModel;
using PIMS.ORM;
using PIMS.Utils;
using PIMS.XmlModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace PIMS
{
    public partial class FormDataDictonary : DockContent
    {
        DataTable emptyDt = new DataTable();
        Dictionary<String, String> mapDict = new Dictionary<string, string>()
        {
            {"id","主键ID" },
            {"type","分类" },
            {"code","代号" },
            {"value","值" }
        };
        Dictionary<String, String> unMapDict = new Dictionary<string, string>()
        {
            {"主键ID","id" },
            {"分类","type" },
            {"代号","code" },
            {"值","value" }
        };
        Dictionary<String, int> lengthLimitDict = new Dictionary<string, int>();

        DataTable dtResult = null;
        BackgroundWorker backgroundWorker = new BackgroundWorker();
        string type = "";

        public FormDataDictonary()
        {
            InitializeComponent();
        }

        private void FormDataDictonary_Load(object sender, EventArgs e)
        {
            this.Text = this.Text +  " <导入Excel方法：先在指定分类导出Excel，用Excel编辑后再导入。>";
            try
            {
                emptyDt.Columns.Add("主键ID", Type.GetType("System.String"));
                emptyDt.Columns.Add("分类", Type.GetType("System.String"));
                emptyDt.Columns.Add("代号", Type.GetType("System.String"));
                emptyDt.Columns.Add("值", Type.GetType("System.String"));

                backgroundWorker.DoWork += this.ExecuteLoadHistory_DoWork;
                backgroundWorker.RunWorkerCompleted += this.ExecuteLoadHistoryInWorker_Completed;

                this.dgv.DataSource = this.emptyDt;
                DgvTools.dataGridView(this.dgv);
                DgvTools.dataGridViewDisableSort(this.dgv);
                this.dgv.SelectionMode=DataGridViewSelectionMode.FullRowSelect;
                this.dgv.Columns["值"].Width = 600;

                List<DataDictionaryXItem> list = Common.pimsConfig.DataDictionary.add;
                this.comboBox1.Items.Clear();
                foreach (DataDictionaryXItem item in list)
                {
                    this.comboBox1.Items.Add(item.name);
                    this.lengthLimitDict.Add(item.name,item.keyLength);
                }
                if (this.comboBox1.Items.Count > 0)
                {
                   // ComboBoxTools.ComboBoxTextCenter(this.comboBox1); //不太好用，取消
                    this.comboBox1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                Common.log.Error("", ex);
                MessageBox.Show(ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        private void LoadHistory()
        {
            backgroundWorker.RunWorkerAsync();
        }

        private void ExecuteLoadHistory_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string cmdSql = string.Concat(new string[]
                {
                    "select * from tb_datadictionary where type = '",
                    this.type,
                    "' "
                });
                DataTable dtTemp = SqlSugarHelper.QueryToDataTable<datadictionary>(cmdSql);
                if (dtTemp == null)
                {
                    dtResult = null;
                    return;
                }
                dtResult = dtTemp;
                for (int i = 0; i < dtResult.Columns.Count; i++)
                {
                    dtResult.Columns[i].ColumnName = mapDict[dtResult.Columns[i].ColumnName];
                }
            }
            catch (Exception ex)
            {
                Common.log.Error("", ex);
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                dtResult = null;
            }
        }

        private void ExecuteLoadHistoryInWorker_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            if (dtResult == null)
            {
                this.dgv.DataSource = this.emptyDt;
            }
            else
            {
                this.dgv.DataSource = this.dtResult;
            }
            this.Err.Clear();
            this.btnAdd.Enabled = true;
            this.btnEdit.Enabled = true;
            this.btnDel.Enabled = true;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.tbKey.Text = "";
            this.tbValue.Text = "";
            this.type = this.comboBox1.Text;
            int limit = lengthLimitDict[this.type];
            if(limit>0)
            {
                this.tbValue.MaxLength = limit;
            }
            else
            {
                this.tbValue.MaxLength = 20;
            }
            LoadHistory();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {            
            try
            {
                this.Err.Clear();
                if(this.comboBox1.SelectedIndex==-1)
                {
                    this.Err.SetError(this.comboBox1,"禁止为空!");
                    return;
                }
                if (String.IsNullOrEmpty(this.tbKey.Text.Trim()))
                {
                    this.Err.SetError(this.tbKey, "禁止为空!");
                    return;
                }

                string where = string.Format("type='{0}' and code='{1}' ", this.comboBox1.Text, this.tbKey.Text.Trim());
                datadictionary datadic = SqlSugarHelper.Query<datadictionary>(where,"");
                if(datadic!=null)
                {
                    this.Err.SetError(this.tbKey, "代号已使用过!");
                    return;
                }

                if (String.IsNullOrEmpty(this.tbValue.Text.Trim()))
                {
                    this.Err.SetError(this.tbValue, "禁止为空!");
                    return;
                }
                where = string.Format("type='{0}' and value='{1}' ", this.comboBox1.Text, this.tbValue.Text.Trim());
                datadic = SqlSugarHelper.Query<datadictionary>(where, "");
                if (datadic != null)
                {
                    this.Err.SetError(this.tbValue, "值已使用过!");
                    return;
                }

                this.btnAdd.Enabled = false;
                datadictionary data = new datadictionary();
                data.type = this.comboBox1.Text;
                data.code = this.tbKey.Text.Trim();
                data.value = this.tbValue.Text.Trim();
                if(SqlSugarHelper.InsertRecord<datadictionary>(data) > 0)
                {
                    LoadHistory();
                }
            }
            catch(Exception ex)
            {
                Common.d.DebugMsg(ex.Message,InfoLevel.error);
                Common.log.Error("", ex);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            this.Err.Clear();
            if (this.comboBox1.SelectedIndex == -1)
            {
                this.Err.SetError(this.comboBox1, "禁止为空!");
                return;
            }
            if (String.IsNullOrEmpty(this.tbKey.Text.Trim()))
            {
                this.Err.SetError(this.tbKey, "禁止为空!");
                return;
            }
            if (String.IsNullOrEmpty(this.tbValue.Text.Trim()))
            {
                this.Err.SetError(this.tbValue, "禁止为空!");
                return;
            }

            try
            {
                DataGridViewRow currentRow = this.dgv.CurrentRow;
                if (currentRow == null)
                {
                    MessageBox.Show("请先选择要修改的行再执行操作!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                this.btnEdit.Enabled = false;
                int id = currentRow.Index;
                int pkValue = Convert.ToInt32(this.dgv.Rows[id].Cells[0].Value);
                datadictionary datadic = SqlSugarHelper.QueryByKey<datadictionary>(pkValue);
                if(datadic != null)
                {
                    string where = string.Format("type='{0}' and code='{1}' ", this.comboBox1.Text, this.tbKey.Text.Trim());
                    List<datadictionary> list = SqlSugarHelper.QueryList<datadictionary>(where, 0);
                    if(list.Count == 1)
                    {
                        if (list[0].id != pkValue)
                        {
                            MessageBox.Show(String.Format("代号{0}重复使用！\r\n值:{1}", 
                                this.tbKey.Text.Trim(), list[0].value), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            this.btnEdit.Enabled = true;
                            return;
                        }
                    }
                    where = string.Format("type='{0}' and value='{1}' ", this.comboBox1.Text, this.tbValue.Text.Trim());
                    list = SqlSugarHelper.QueryList<datadictionary>(where, 0);
                    if (list.Count == 1)
                    {
                        if (list[0].id != pkValue)
                        {
                            MessageBox.Show(String.Format("值{0}重复使用！\r\n代号:{1}", 
                                this.tbValue.Text.Trim(), list[0].code), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            this.btnEdit.Enabled = true;
                            return;
                        }
                    }

                    if(datadic.code != this.tbKey.Text.Trim() || datadic.value!= this.tbValue.Text.Trim())
                    {
                        if (MessageBox.Show(String.Format("确定修改数据吗?\r\n分类:{0}\r\n原 代号:{1}\r\n原 值:{2}\r\n\r\n新 代号:{3}\r\n新 值:{4}",
                           this.comboBox1.Text, datadic.code, datadic.value,
                           this.tbKey.Text.Trim(), this.tbValue.Text.Trim()), "注意", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                        {
                            this.btnEdit.Enabled = true;
                            return;
                        }                           

                        datadic.code = this.tbKey.Text.Trim();
                        datadic.value = this.tbValue.Text.Trim();
                        SqlSugarHelper.UpdateRecord<datadictionary>(datadic);
                        LoadHistory();
                    }
                    else
                    {
                        MessageBox.Show("无变更！","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        this.btnEdit.Enabled = true;
                    }
                }
                else
                {
                    MessageBox.Show(string.Format("主键:{0}无记录！",pkValue.ToString()),"NG");
                    this.btnEdit.Enabled = true;
                }                
            }
            catch (Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                Common.log.Error("", ex);
                this.btnEdit.Enabled = true;
            }
            
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            this.Err.Clear();
            try
            {                
                if (this.dgv.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请先选择要修改的行再执行操作!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                this.btnDel.Enabled = false;
                List<int> pkValueList = new List<int>();
                for(int i=0;i< this.dgv.SelectedRows.Count;i++)
                {
                    pkValueList.Add(Convert.ToInt32(this.dgv.SelectedRows[i].Cells[0].Value));
                }
                string cmdSql= string.Concat(new string[]
                {
                   "select * from tb_datadictionary where "
                 });
                foreach(int pk in pkValueList)
                {
                    cmdSql += " id = " + pk.ToString()+ " or";
                }
                cmdSql = cmdSql.Substring(0,cmdSql.Length-2);
                List<datadictionary> datadic = SqlSugarHelper.Query<datadictionary>(cmdSql);
                if(datadic != null)
                {
                    string msg = "";
                    foreach(datadictionary da in datadic)
                    {
                        msg += String.Format("\r\n代号:{0} 值:{1}",da.code,da.value);
                    }
                    if (MessageBox.Show(String.Format("确定删除数据吗?\r\n分类:{0}\r\n{1}",
                     this.comboBox1.Text, msg), "注意", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                    {
                        this.btnDel.Enabled = true;
                        return;
                    }
                    foreach (datadictionary da in datadic)
                    {
                        SqlSugarHelper.DeleteRecordByKey<datadictionary>(da.id);
                    }
                    LoadHistory();
                }
                else
                {
                    MessageBox.Show(string.Format("无记录！"), "NG");
                    this.btnDel.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                Common.log.Error("", ex);
                this.btnDel.Enabled = true;
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dtInfo = DgvTools.DataGridViewToDataTable(this.dgv);
                dtInfo.TableName = this.comboBox1.Text;
                dtInfo.Columns.Remove("主键ID");
                dtInfo.Columns.Remove("分类");
                if (dtInfo.Rows.Count == 0) return;

                this.btnExport.Enabled = false;
                string filename = this.comboBox1.Text + "导出.xls";

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title = "";
                sfd.FileName = filename;
                sfd.InitialDirectory= Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                sfd.Filter = "导出Excel文件|.xls";
                if (DialogResult.OK == sfd.ShowDialog())
                {
                    string path = sfd.FileName;
                    if (path == "")
                    {
                        return;
                    }
                    NPOIHelper.RenderDataTableToExcel(dtInfo, path);
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                    
                }
                this.btnExport.Enabled = true;
            }
            catch(Exception ex)
            {
                Common.d.DebugMsg(ex.Message, InfoLevel.error);
                Common.log.Error("", ex);
                this.btnExport.Enabled = true;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx";
                ofd.ValidateNames = true;
                ofd.CheckPathExists = true;
                ofd.CheckFileExists = true;
                //设置默认打开路径(绝对路径)
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string strFileName = ofd.FileName;
                    //其他代码
                    DataTable dtIn = null;
                    if(strFileName.ToLower().EndsWith("xlsx"))
                    {
                        //dtIn = NPOIHelper.RenderDataTableFromExcelX(NPOIHelper.OpenFile(strFileName), this.comboBox1.Text);
                        MessageBox.Show("只支持xls格式导入！", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    else if(strFileName.ToLower().EndsWith("xls"))
                    {
                        dtIn = NPOIHelper.RenderDataTableFromExcel(NPOIHelper.OpenFile(strFileName), this.comboBox1.Text);
                    }                    
                    if(dtIn != null && dtIn.Rows.Count>0)
                    {
                        if (MessageBox.Show(String.Format("导入数据会清空现有分类下的所有数据，确定导入数据吗?\r\n分类:{0}",
                           this.comboBox1.Text), "注意", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                        {
                            this.btnImport.Enabled = true;
                            return;
                        }
                        List<datadictionary> list = new List<datadictionary>();
                        for(int i=0;i< dtIn.Rows.Count;i++)
                        {
                            datadictionary da = new datadictionary();
                            da.type = this.comboBox1.Text;
                            da.code = dtIn.Rows[i][0].ToString();
                            da.value = dtIn.Rows[i][1].ToString();
                            list.Add(da);
                        }

                        string where = string.Format("type='{0}'",this.comboBox1.Text);
                        SqlSugarHelper.DeleteRecord<datadictionary>(where);
                        foreach (datadictionary d in list)
                        {
                            SqlSugarHelper.InsertRecord<datadictionary>(d);
                        }

                        LoadHistory();
                        MessageBox.Show("导入成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }                 
                }
                this.btnImport.Enabled = true;
            }
            catch(Exception ex)
            {
                Common.log.Error("", ex);
                MessageBox.Show("导入失败！", ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.btnImport.Enabled = true;
            }
        }

        private void dgv_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void dgv_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewRow currentRow = this.dgv.CurrentRow;
            if (currentRow == null)
            {
                this.tbKey.Text = "";
                this.tbValue.Text = "";
                return;
            }
            int id = currentRow.Index;
            this.tbKey.Text = this.dgv.Rows[id].Cells[2].Value.ToString();
            this.tbValue.Text = this.dgv.Rows[id].Cells[3].Value.ToString();
        }
    }
}
